package com.example.fragmentdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.fragmentdemo1.R;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btn_Info,btn_Contact,btn_Dynamic;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_Info=(Button) findViewById(R.id.btn_Info);
        btn_Contact=(Button) findViewById(R.id.btn_Contact);
        btn_Dynamic=(Button) findViewById(R.id.btn_Dynamic);
        btn_Info.setOnClickListener(this);
        btn_Contact.setOnClickListener(this);
        btn_Dynamic.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_Info:
                InfoFragment infoFragment=new InfoFragment();   //创建Fragment对象实例
                setFragment(infoFragment);                      //添加Fragment到Activity
                btn_Info.setBackgroundColor(Color.YELLOW);      //设置当前按钮背景为黄色
                btn_Contact.setBackgroundColor(Color.WHITE);
                btn_Dynamic.setBackgroundColor(Color.WHITE);
                break;
            case R.id.btn_Contact:
                ContactFragment contactFragment=new ContactFragment();
                setFragment(contactFragment);
                btn_Info.setBackgroundColor(Color.WHITE);
                btn_Contact.setBackgroundColor(Color.YELLOW);
                btn_Dynamic.setBackgroundColor(Color.WHITE);
                break;
            case R.id.btn_Dynamic:
                DynamicFragment dynamicFragment=new DynamicFragment();
                setFragment(dynamicFragment);
                btn_Info.setBackgroundColor(Color.WHITE);
                btn_Contact.setBackgroundColor(Color.WHITE);
                btn_Dynamic.setBackgroundColor(Color.YELLOW);
                break;
        }
    }

    private void setFragment(Fragment fragment){
        FragmentManager fm=getSupportFragmentManager();  //获取FragmentManager对象
        FragmentTransaction ft=fm.beginTransaction();    //获取FragmentTransaction对象
        ft.replace(R.id.main_frame_layout,fragment);     //添加Fragment对象到Activity
        ft.commit();                                     //事务提交
    }
}
